package com.imesne.office.excel.read;

import com.imesne.office.excel.model.ExcelBook;
import com.imesne.office.excel.model.ExcelSheet;
import com.imesne.office.excel.utils.ExcelKitUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;

/**
 * Created by liyd on 17/7/3.
 */
public class ExcelBookReaderImpl extends AbstractConfigReader implements ExcelBookReader {

    public ExcelBook readExcelBook(byte[] bytes) {
        ExcelBook excelBook = new ExcelBook();
        Workbook workbook = null;
        try {
            workbook = ExcelKitUtils.createWorkbook(bytes);

            ExcelSheetReader excelSheetReader = this.getExcelReaderConfig().getExcelSheetReader();
            int numberOfSheets = workbook.getNumberOfSheets();
            for (int i = 0; i < numberOfSheets; i++) {

                Sheet sheet = workbook.getSheetAt(i);
                if (!excelSheetReader.isSupportRead(workbook, sheet, i)) {
                    continue;
                }
                ExcelSheet excelSheet = excelSheetReader.readExcelSheet(workbook, sheet, i);

                int mode = AbstractExcelReadProcessor.CONTINUE;
                if (this.getExcelReaderConfig().getExcelReadProcessor() != null) {
                    mode = this.getExcelReaderConfig().getExcelReadProcessor().processExcelSheet(excelSheet, sheet, workbook, i);
                }

                if (mode == AbstractExcelReadProcessor.CONTINUE) {
                    excelBook.addSheet(excelSheet);
                } else if (mode == AbstractExcelReadProcessor.STOP_INCLUSIVE) {
                    excelBook.addSheet(excelSheet);
                    break;
                } else if (mode == AbstractExcelReadProcessor.STOP_EXCLUSIVE) {
                    break;
                }
            }
            if (this.getExcelReaderConfig().getExcelReadProcessor() != null) {
                this.getExcelReaderConfig().getExcelReadProcessor().processExcelBook(excelBook, workbook, bytes);
            }
        } finally {
            IOUtils.closeQuietly(workbook);
        }
        return excelBook;
    }
}
